<template>
	<view>
		<cu-custom :isBack="true">
			<block style="color: #333333;font-size: 48rpx;" slot="content">注册</block>
		</cu-custom>
		<button @click="create">创建websocket链接</button>
		<button @click="send">发送数据</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				websocket: '',
				websocketStatus: false,
				socketMsgQueue: []
			}
		},
		onLoad() {
			uni.onSocketOpen(function(res) {
				console.log('WebSocket连接已打开！')
				this.websocketStatus = true
				for (var i = 0; i < this.socketMsgQueue.length; i++) {
					this.sendSocketMessage(socketMsgQueue[i])
				}
				this.socketMsgQueue = [];
			});
			uni.onSocketError(function(res) {
				console.log('WebSocket连接打开失败，请检查！')
			});
			uni.onSocketClose(function(res) {
				console.log('WebSocket 已关闭！')
				this.websocketStatus = false
			});
		},
		methods: {
			create() {
				this.websocket = uni.connectSocket({
					url: 'wss://1o669531n3.imwork.net:29545?mac=2',
					complete: () => {}
				});
			},
			send() {
				let msg = {
					"name": "lisi",
					"age": 18
				}
				if (websocketStatus) {
					uni.sendSocketMessage({
						data: msg
					});
				} else {
					this.socketMsgQueue.push(msg)
				}
			}
		}
	}
</script>

<style>

</style>
